%%-*- mode: erlang -*-

%% ==============================================================================
%% Relx configs
%% ==============================================================================
Keyfind = fun(K, L) -> {K, V} = lists:keyfind(K, 1, L), V end,

IsCentos6 = fun() ->
                case file:read_file("/etc/centos-release") of
                    {ok, <<"CentOS release 6", _/binary >>} ->
                        true;
                    _ ->
                        false
                end
            end,

IsWin32 = fun() ->
                win32 =:= element(1, os:type())
          end,

IsMacOS = fun() ->
               {unix, darwin} =:= os:type()
          end,

IsQuicSupp = fun() ->
                not (IsCentos6() orelse IsWin32() orelse IsMacOS()
                     orelse false =/= os:getenv("BUILD_WITHOUT_QUIC")
                    )
             end,

NewRelx =
    fun(Name, Profiles) ->
        EMQTT = Keyfind(Name, Profiles),
        Relx = Keyfind(relx, EMQTT),
        {release, {emqtt, Vsn}, Apps} = lists:keyfind(release, 1, Relx),
        GitDescribe = lists:last(string:tokens(os:cmd("git describe --tags --always"), "\n")),
        lists:keystore(release, 1, Relx, {release, {emqtt, GitDescribe},
                                          Apps ++ [ {quicer, load} || IsQuicSupp() ]})
    end,

Profiles = Keyfind(profiles, CONFIG),
NewProfiles = lists:foldl(fun(Key, Acc) ->
                                  {Key, Old} = lists:keyfind(Key, 1, Acc),
                                  New = lists:keystore(relx, 1, Old, {relx, NewRelx(Key, Acc)}),
                                  lists:keystore(Key, 1, Acc, {Key, New})
                          end, Profiles, [emqtt, emqtt_pkg, emqtt_relup_test]),

NewConfig = lists:keystore(profiles, 1, CONFIG, {profiles, NewProfiles}),

Quicer = {quicer, {git, "https://github.com/emqx/quic.git", {tag, "0.0.16"}}},
KillQuicer = fun(C) ->
                {deps, Deps0} = lists:keyfind(deps, 1, C),
                {erl_opts, ErlOpts0} = lists:keyfind(erl_opts, 1, C),
                IsQuic = IsQuicSupp(),
                New = [ {deps, Deps0 ++ [ Quicer || IsQuic ]}
                      , {erl_opts, ErlOpts0 ++ [ {d, 'BUILD_WITHOUT_QUIC'} || not IsQuic ]}
                      ],
                lists:foldl(fun({Key, _Val} = KV, Acc) ->
                                    lists:keystore(Key, 1, Acc, KV)
                            end, C, New)
            end,
KillQuicer(NewConfig).
